package com.yangyouli.unity_demo_server.transaction;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.yangyouli.unity_demo_server.annotation.Transaction;
import com.yangyouli.unity_demo_server.container.SqlSessionHolder;
import com.yangyouli.unity_demo_server.util.ConnUtil;
import com.yangyouli.unity_demo_server.util.ThreadLocalHelper;

public class TransactionInterceptor implements InvocationHandler {
	private Object target;
	
	public TransactionInterceptor (Object target) {
		this.target = target;
	}
	
	public Object getObject () {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object result = null;
		SqlSessionHolder sessionHolder = null;
		System.out.println("进入代理");
		// 被注解的方法才能回滚
		if (!method.isAnnotationPresent(Transaction.class)) {
			return method.invoke(target, args);
		} else {
			try {
				sessionHolder = ThreadLocalHelper.getSqlSessionHolder(ConnUtil.getSqlSessionFactory());
				System.out.println(target + "被代理 方法为：" + method);
				result = method.invoke(target, args);
			} catch (Exception e) {
				sessionHolder.rollback();
				e.printStackTrace();
			} finally {
				sessionHolder.close();
			}
			return result;
		}
	}
	
}
